(function($){
	var KEY = "jforest.fileManager";
	
	var FileManager = function(element,options){
		this.$el = $(element);
		this.options = $.extend({
			type:1,
			token:'token',
			multiple:false,
			limit:5,
			parent:null,
			resDomain:'',
			resPathKey:'mng',
			resPath:'',
			addImgPath:'',
			resType:'auto',	//资源类型，image,video,auto
			path:null,
			selectedCallback:function(){return true;},
			layer:{}
		},options);
		
		this.currPath = this.$el.hide().val();

		if(!$.isFunction(this.options.selectedCallback)){
			this.options.selectedCallback = function(){return true;}
		}

		if(this.options.type == 1){
			if(!this.options.addImgPath){
				this.options.addImgPath = this.options.resDomain + this.options.resPath+ '/assets/jforest-2.0.0/css/imgs/add.png';
			}
			this._createUi();
		}
	};

	FileManager.prototype = {
		_createUi:function(){
			var self = this;
			this.packDiv = this.$el.wrap('<div class="jf-file-manage clearfix"></div>').parent();
			if(this.options.multiple){
				this.packDiv.append('<div class="images"></div>');
				var hideAdd = false;
				if(this.currPath){
					var arr = this.currPath.split('|');
					for(var i=0;i<arr.length;i++){
						this._buildMultipleImg(arr[i]);
					}
					if(this.options.limit <= arr.length){
						hideAdd = true;
					}
				}
				
				var addImgPath = this.options.addImgPath;
				$('<div class="img-thumbnail jf-x-add-img-btn">'
					+'<img src="'+addImgPath+'" class="img-responsive" style="width:100%;"/></div>').appendTo(this.packDiv).click(function(){
					self.select();
				});
				if(hideAdd){
					self.packDiv.find('.jf-x-add-img-btn').hide();
				}
			}else{
				if(this.currPath){
					//检查后缀
					var imgPath = this.options.resDomain + this.options.resPath+ '/assets/jforest-2.0.0/css/imgs/file01.jpg';
					var index = this.currPath.lastIndexOf('.');
					if(index > 0){
						var suffix = this.currPath.substr(index);
						if(suffix == '.jpg' || suffix == '.png' || suffix == '.jpeg'){
							imgPath = this.options.resDomain + this.options.resPath + this.currPath;
						}
					}					
					var html = '<div class="img-thumbnail pull-left" data-path="'+this.currPath+'">'
						+'<img src="'+imgPath+'" class="img-responsive" style="width:100%;"/>'
						+'<div class="btn-panel"><button type="button" class="close"><span>&times;</span></button></div></div>';
					$(html).appendTo(this.packDiv).click(function(){
						self.select();
					}).find('.close').click(function(){
						self.close(this);
					});
				}else{
					var addImgPath = this.options.addImgPath;
					var html = '<div class="img-thumbnail">'
							+'<img src="'+addImgPath+'" class="img-responsive" style="width:100%;"/></div>';
					$(html).appendTo(this.packDiv).click(function(){
						self.select();
					});
				}
			}
		},
		_buildMultipleImg:function(path,imgPath){
			var self = this;
			if(!imgPath || imgPath == ''){imgPath = path;}
			imgPath = this.options.resDomain + this.options.resPath + imgPath;
			var html = '<div class="img-thumbnail pull-left" data-path="'+path+'">'
				+'<img src="'+imgPath+'" class="img-responsive" style="width:100%;"/>'
				+'<div class="btn-panel">'
					+'<a href="javascript:void(0);" class="pull-left"><i class="fa fa-arrow-left"/></a>'
					+'<a href="javascript:void(0);" class="pull-left"><i class="fa fa-arrow-right"/></a>'
					+'<button type="button" class="close"><span>&times;</span></button></div>'
				+'</div>';
			html = $(html).appendTo(self.packDiv.find('.images'));
			html.find('.close').click(function(){
				self.close(this);
			});
			html.find('.fa-arrow-left').parent().click(function(){
				if(html.prev()){
					html.after(html.prev());
					var paths = '';
					self.packDiv.find('.images .img-thumbnail').each(function(i,e){
						var path = $(e).data('path');
						if(path){
							paths = paths + '|' +path;
						}
					});
					if(paths.indexOf('|')==0){
						self.$el.val(paths.substr(1));
					}else{
						self.$el.val(paths);
					}
				}
			});
			html.find('.fa-arrow-right').parent().click(function(){
				if(html.next()){
					html.before(html.next());
					var paths = '';
					self.packDiv.find('.images .img-thumbnail').each(function(i,e){
						var path = $(e).data('path');
						if(path){
							paths = paths + '|' +path;
						}
					});
					if(paths.indexOf('|')==0){
						self.$el.val(paths.substr(1));
					}else{
						self.$el.val(paths);
					}
				}
			});
			return html;
		},
		set:function(path,imgPath){
			var self = this,opt = this.options;
			if(path && path != ''){
				var flag = opt.selectedCallback.apply(self,[path]);
				if(flag){
					if(self.options.multiple){
						var paths = self.$el.val();
						paths = paths + '|' +path;
						if(paths.indexOf('|')==0){
							self.$el.val(paths.substr(1));
						}else{
							self.$el.val(paths);
						}
						if(opt.type == 1){
							self._buildMultipleImg(path,imgPath);
							var arr = paths.split('|');
							if(self.options.limit <= arr.length){
								//隐藏新增按钮
								self.packDiv.find('.jf-x-add-img-btn').hide();
							}
						}
					}else{
						if(!imgPath || imgPath == ''){imgPath = path;}
						imgPath = self.options.resDomain  + this.options.resPath + imgPath;
						self.$el.val(path);
						if(opt.type == 1){
							self.packDiv.find('.img-thumbnail img').attr('src',imgPath);
							if(self.packDiv.find('.img-thumbnail .close').length == 0){
								var html = '<div class="btn-panel"><button type="button" class="close"><span>&times;</span></button></div>';
								$(html).appendTo(self.packDiv.find('.img-thumbnail')).find('.close').click(function(){
									self.close(this);
								});
							}
						}
					}
				}
			}else if(!self.options.multiple){
				self.clear();
			}
		},
		clear:function(){
			var self = this;
			self.$el.val('');
			if(self.options.multiple){
				self.packDiv.find('.images').empty();
				self.packDiv.find('.jf-x-add-img-btn').show();
			}else{
				self.packDiv.find('.img-thumbnail img').attr('src',self.options.addImgPath);
				self.packDiv.find('.img-thumbnail .btn-panel').remove();
			}
		},
		select:function(){
			var self = this,opt = this.options;
			var key ='jforest_fm_'+new Date().getTime();
			var path = '';
			if(opt.path) {path = encodeURI(opt.path);}
			var config = $.extend({
				type: 2
				,title: '图片管理器'
				,content:[opt.resDomain+'/'+opt.resPathKey+'/file/manage.html?token='+opt.token+'&key='+key+'&resType='+opt.resType+'&path='+path,'no']
				,area:['800px','480px']
				,btn: ['确定', '关闭']
			    ,yes: function(index, layero){
			    	$.ajax({
		                async : false,
		                url : opt.resDomain+'/'+opt.resPathKey+'/file/select/get.do',
		                type : "POST",
		                //dataType:'json',
		                dataType : "jsonp", // 返回的数据类型，设置为JSONP方式
		                jsonp : 'jsoncallback', //指定一个查询参数名称来覆盖默认的 jsonp 回调参数名 callback
		                jsonpCallback: '_get', //设置回调函数名
		                data : {key:key,token:self.options.token}, 
		                success: function(result, status, xhr){
		                	if(result.code == 200){
		                		if(opt.parent){
		    						opt.parent.layer.close(index);
		    					}else{
		    						layer.close(index);
		    					}
		                		self.set(result.body.filePath,result.body.imgPath);
			    			}else{
			    				if(opt.parent){
			    					opt.parent.layer.msg(result.msg,{icon: 2});
		    					}else{
		    						layer.msg(result.msg,{icon: 2});
		    					}
			    			}
		                }
		            });
				}
			},opt.layer);
			
			if(opt.parent){
				opt.parent.layer.open(config);
			}else{
				layer.open(config);
			}
		},
		close:function(el){
			var paths = '';
			if(this.options.multiple){
				$(el).parents('.img-thumbnail').remove();
				this.packDiv.find('.images .img-thumbnail').each(function(i,e){
					var path = $(e).data('path');
					if(path){
						paths = paths + '|' + path;
					}
				});
				if(paths.indexOf('|')==0){
					paths = paths.substr(1);
				}
				
				if(this.packDiv.find('.jf-x-add-img-btn').is(":hidden")){
					var arr = paths.split('|');
					if(this.options.limit > arr.length){
						//显示新增按钮
						this.packDiv.find('.jf-x-add-img-btn').show();
					}
				}
			}else{
				var addImgPath = this.options.addImgPath;
				$(el).parents('.img-thumbnail').find('img').attr('src',addImgPath);
				$(el).parent().remove();
			}
			this.$el.val(paths);
			event.stopPropagation();
		}
	};
	
	$.fn.jfFileManager = function(){
		var args = Array.prototype.slice.call(arguments, 0);
		var value = undefined;
		this.each(function () {
			var $this = $(this);
			if (args.length === 0 || typeof(args[0]) === "object") {
				opts = args.length === 0 ? {} : $.extend({}, args[0]);
				value = new FileManager(this,opts);//创建控件
				$this.data(KEY,value); 
			}else if (typeof(args[0]) === "string"){
				var entity = $this.data(KEY);
                if(entity === undefined){return;}
                value = entity[args[0]].apply(entity, args.slice(1));
			}else{
				 throw 'Invalid arguments to '+KEY+' plugin: ' + args;
			}
	    });
	    return (value === undefined) ? this : value;
	};
	
	$.fn.jfFileManager.Constructor = FileManager;
	
})(window.jQuery)
